// 云函数入口文件
const cloud = require('wx-server-sdk')

// 错误码
const ERROR_CODE = {
  NOT_FOUND: 10001,  // 画板不存在
  NOT_MEMBER: 10002, // 不是画板的成员
  PAREM_EMPTY: 10003, // 参数为空
  NOT_EDIT_AUTH: 10004, // 没有编辑权限
}

function dateFormat(date) {
  return date.toJSON().substr(0, 19).replace('T', ' ');;
}

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { drawBoardId, auth, userInfo } = event;
  try {
    // 获取 id 对应画板数据
    const drawBoardDatas = await db.collection('drawBoards').where({
      _id: drawBoardId
    }).get();

    // 画板不存在
    if (!drawBoardDatas.data.length) {
      return {
        data: {},
        code: ERROR_CODE.NOT_FOUND,
        msg: 'drawBoard not found'
      }
    }

    const drawBoardData = drawBoardDatas.data[0];
    const { owner, members } = drawBoardData;

    if (owner.openId === OPENID) {
      // 如果当前是创建者, 则无法改变权限
      return {
        data: {},
        code: 0,
        msg: 'success'
      }
    }

    // 如果之前成员已存在且权限没有发生改变, 直接返回成功
    if (members[OPENID] && members[OPENID].auth === auth) {
      return {
        data: {},
        code: 0,
        msg: 'success'
      }
    }

    // 更新或新增成员
    const { avatarUrl, nickName } = userInfo;
    members[OPENID] = {
      auth,
      avatarUrl,
      nickName
    }
    await db.collection('drawBoards').where({
      _id: drawBoardId
    }).update({
      data: {
        members,
        updateDate: dateFormat(new Date(Date.now() + 8 * 60 * 60 * 1000)),
      }
    })

    return {
      data: {},
      code: 0,
      msg: 'success'
    }
  } catch (err) {
    return {
      code: 1,
      msg: err,
      data: {}
    }
  }
}